import re

import requests

from database.db import get_invalid_movie, set_movie_online_verified


def check_link(link):
    try:
        resp = requests.get(link, headers={
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36'},
                            timeout=30)
        site = re.findall('(http[s]?://.*?)/', link)[0]
        m3u8 = site + re.findall(r'([0-9a-z/A-Z]+\.m3u8)', resp.text)[0]
        mp4 = site + re.findall(r'([0-9a-z/A-Z]+\.mp4)', resp.text)[0]
        pic = site + re.findall(r'pic = "([0-9a-z/.A-Z]+)"', resp.text)[0]
        print(m3u8)
        return True, (m3u8, mp4, pic)
    except:
        pass
    return False, None


def check():
    while movie := get_invalid_movie():
        online = movie['online']
        verified = []
        print('-' * 80)
        print(movie['title'])
        for item in online:
            link = item['video_link']
            valid, source = check_link(link)
            if valid:
                item['source'] = source
                verified.append(item)
                print(item['title'], link, '有效')
            else:
                print(item['title'], link, '无效')
                try:
                    if movie['category']['category'] in ['国剧', '欧美剧', '日韩']:
                        break
                except:
                    break
        set_movie_online_verified(movie, verified, 1 if verified else -1)


if __name__ == '__main__':
    check()
